package com.harmontronics.hanma.paas.paas.interceptor;


import com.harmontronics.hanma.paas.paas.annotation.TokenValidSkip;
import com.harmontronics.hanma.paas.paas.consts.DbConstants;
import com.harmontronics.hanma.paas.paas.consts.NumberEnum;
import com.harmontronics.hanma.paas.paas.domain.tenant.entity.HmTenant;
import com.harmontronics.hanma.paas.paas.domain.tenant.entity.HmTenantUser;
import com.harmontronics.hanma.paas.paas.domain.tenant.service.HmTenantAppService;
import com.harmontronics.hanma.paas.paas.exception.TokenErrorException;
import com.harmontronics.hanma.paas.paas.service.HmTenantExtService;
import com.harmontronics.hanma.paas.paas.service.HmTenantUserAppService;
import com.harmontronics.hanma.paas.paas.service.IHmTenantUserService;
import com.harmontronics.hanma.paas.paas.token.AppUserTokenKit;
import com.harmontronics.hanma.paas.paas.token.TenantUserTokenKit;
import com.harmontronics.hanma.paas.paas.token.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ldb 2020/5/11.
 */
@Slf4j
public class TokenValidInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private IHmTenantUserService hmTenantUserAppService;
    @Autowired
    private HmTenantExtService hmTenantExtService;

    @Autowired
    private TenantUserTokenKit tenantUserTokenKit;

    @Autowired
    private AppUserTokenKit appUserTokenKit;

    @Autowired
    private HmTenantAppService hmTenantAppService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return super.preHandle(request, response, handler);
        }
        HandlerMethod method = (HandlerMethod) handler;
        //判断是否有URL白名单注解
        TokenValidSkip tokenValidSkip = method.getMethodAnnotation(TokenValidSkip.class);
        if (tokenValidSkip != null) {
            return true;
        }


        Boolean appPreview = tenantUserTokenKit.getPreview();
        if (appPreview) {
            try {
                appUserTokenKit.renew();
            } catch (TokenErrorException ex) {
                response.setStatus(ex.getStatus());
                return false;
            }

        } else {
            UserInfo userInfo = null;
            try {
                userInfo = tenantUserTokenKit.renew();
            } catch (TokenErrorException ex) {
                response.setStatus(ex.getStatus());
                return false;
            }

            HmTenant hmTenant = hmTenantExtService.findById(userInfo.getTenantId());
            //判断租户是否存在、是否删除、是否禁用
            if (hmTenant == null || hmTenant.getDeleted() == NumberEnum.ONE.getNum() || hmTenant.getStatus() == NumberEnum.ONE.getNum()) {
                writeInfo(response);
                return false;
            }


            HmTenantUser user = hmTenantUserAppService.findById(userInfo.getUserId());

            //判断用户是否存在、是否删除、是否禁用
            if (user == null || user.getDeleted() == NumberEnum.ONE.getNum() || user.getStatus() == NumberEnum.ONE.getNum()) {
                writeInfo(response);
                return false;
            }
        }


        String appUnique = tenantUserTokenKit.getAppUnique();
        if (!DbConstants.DS_MASTER_NAME.equals(appUnique) && hmTenantAppService.isLocked(appUnique)) {
            response.setStatus(HttpStatus.UNAVAILABLE_FOR_LEGAL_REASONS.value());
            return false;
        }

        return true;
    }

    private void writeInfo(HttpServletResponse response) {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
    }
}
